<?php
header('Content-Type: application/json');

require_once '../config.php';

// 跨域设置
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// 只允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'success' => false,
        'error' => '只支持 POST 请求'
    ]);
    exit;
}

// 获取输入的URL
$input = json_decode(file_get_contents('php://input'), true);
$url = $input['url'] ?? ($_POST['url'] ?? '');

// 验证URL参数
if (empty($url)) {
    echo json_encode([
        'success' => false,
        'error' => '缺少参数 url'
    ]);
    exit;
}

if (!filter_var($url, FILTER_VALIDATE_URL)) {
    echo json_encode([
        'success' => false,
        'error' => '参数 url 不是有效的网址'
    ]);
    exit;
}

// 生成短码函数
function generateShortCode() {
    return substr(md5(uniqid(mt_rand(), true)), 0, 6);
}

$shortCode = '';
$maxAttempts = 5;
$attempt = 0;

// 确保生成唯一的短码
while ($attempt < $maxAttempts) {
    $shortCode = generateShortCode();
    $stmt = $pdo->prepare("SELECT id FROM short_urls WHERE short_code = :code LIMIT 1");
    $stmt->execute([':code' => $shortCode]);
    if (!$stmt->fetch()) {
        break;
    }
    $attempt++;
}

// 检查是否成功生成唯一短码
if ($attempt >= $maxAttempts) {
    echo json_encode([
        'success' => false,
        'error' => '无法生成唯一短码，请稍后再试'
    ]);
    exit;
}

// 保存到数据库
$stmt = $pdo->prepare("INSERT INTO short_urls (short_code, original_url, created_at) VALUES (:code, :url, NOW())");
$success = $stmt->execute([
    ':code' => $shortCode,
    ':url' => $url
]);

if (!$success) {
    echo json_encode([
        'success' => false,
        'error' => '保存到数据库失败'
    ]);
    exit;
}

// 自动获取当前域名和协议
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$domain = $_SERVER['HTTP_HOST'];
$baseUrl = $protocol . '://' . $domain;

// 生成短链接
$shortUrl = $baseUrl . '/redirect.php?code=' . $shortCode;

// 返回结果
echo json_encode([
    'success' => true,
    'short_code' => $shortCode,
    'short_url' => $shortUrl,
    'original_url' => $url,
    'created_at' => date('Y-m-d H:i:s'),
    'message' => '短链创建成功'
]);
?>
